package com.slz3.business.module.goodsManagement.gooTypeLevel2.service;

import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.steward.PageableSteward;
import com.slz3.business.module.goodsManagement.gooGoods.domain.GooGoods;
import com.slz3.business.module.goodsManagement.gooTypeLevel1.domain.GooTypeLevel1;
import com.slz3.business.module.goodsManagement.gooTypeLevel2.domain.GooTypeLevel2;
import com.slz3.business.module.goodsManagement.gooTypeLevel2.domain.GooTypeLevel2Factory;
import com.slz3.business.module.goodsManagement.gooTypeLevel2.steward.GooTypeLevel2Specification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GooTypeLevel2ServiceImpl implements GooTypeLevel2Service {

    @Override
    public GooTypeLevel2 save(GooTypeLevel2 gooTypeLevel2) {
        return Repositorys.gooTypeLevel2.save(GooTypeLevel2Factory.initBaseFields(gooTypeLevel2));
    }

    @Override
    public Page<GooTypeLevel2> page(MultiValueMap<String, String> params) {
        Page<GooTypeLevel2> gooTypeLevel2Page = Repositorys.gooTypeLevel2.findAll(
                GooTypeLevel2Specification.findJoin(params), PageableSteward.extract(params)
        );
        Map<UUID, GooTypeLevel1> joinLevel1 = Repositorys.gooTypeLevel1.findAllById(
                gooTypeLevel2Page.getContent().stream().map(GooTypeLevel2::getSerOneId).collect(Collectors.toList())
        ).stream().collect(Collectors.toMap(GooTypeLevel1::getUuid, Function.identity()));
        gooTypeLevel2Page.getContent().stream().forEach(item -> item.setGooTypeLevel1(joinLevel1.get(item.getSerOneId())));
        return gooTypeLevel2Page;
    }

    @Override
    public GooTypeLevel2 modify(GooTypeLevel2 gooTypeLevel2New) {
        return Repositorys.gooTypeLevel2.saveAndFlush(GooTypeLevel2Factory.initBaseFields(gooTypeLevel2New));
    }

    @Override
    public Optional<GooTypeLevel2> single(UUID uuid) {
        return Repositorys.gooTypeLevel2.findById(uuid);
    }

    @Override
    public List<GooTypeLevel2> findAllByUuids(Iterable<UUID> uuids) {
        return Repositorys.gooTypeLevel2.findAllById(uuids);
    }

    @Override
    public List<GooTypeLevel2> delete(List<GooTypeLevel2> gooTypeLevel2List) {
        gooTypeLevel2List.stream().forEach(item -> {
            item.setValidFlag(ValidFlag.DEL);
            GooTypeLevel2Factory.initBaseFields(item);
        });
        return Services.gooTypeLevel2Transactional.batchModify(gooTypeLevel2List);
    }

}
